const request = require('superagent');
const puppeteer = require('puppeteer');
const events = require('events');


const width = 1200;
const height = 800;

const [__dir,__file,username,password] = process.argv;

const eventsEmitter = new events.EventEmitter();

const f = async(serverPool,jsessionid) => {
    const res = await request.post('http://xk.ccnu.edu.cn/cjcx/cjcx_cxDgXscj.html')
    .query({doType:'query'})
    .set('Cookie',`BIGipServerpool_jwc_xk=${serverPool}; JSESSIONID=${jsessionid}`)
    .set('Content-Type','application/x-www-form-urlencoded;charset=UTF-8')
    .send({'queryModel.showCount':100})
    .accept('application/json')
    let allCourses = JSON.parse(res.text);
    const map = new Map();
    allCourses = allCourses.items;
    let passedCourses = allCourses.filter(course=>course.cj>60);
    // console.log(`有${allCourses.length-passedCourses.length}门课没有过!`);
    // console.log(passedCourses.filter(course=>course.kcxzmc==='专业主干课程').map(course=>course.kcmc));
    passedCourses.forEach(course=>{
        map.has(course.kcxzmc)?map.set(course.kcxzmc,Number(course.xf) + Number(map.get(course.kcxzmc))):map.set(course.kcxzmc,course.xf);
    })
    
    console.log(map);
}

eventsEmitter.on('getData',f);

(async() => {
    const browser = await puppeteer.launch();
    let page = await browser.newPage();
    await page.setViewport({width,height});
    await page.goto('http://one.ccnu.edu.cn');
    await page.type('#username',username);
    await page.type('#password',password);
    await page.click('.btn-submit');
    //选择教学教务
    await page.waitForNavigation();
    await page.waitFor(1000);
    await page.evaluate(()=>{
        document.querySelectorAll('li')[29].setAttribute('id','xiongxin');
    });
    await page.click('#xiongxin');

    await page.waitFor(1000);
    let pages = await browser.pages();
    page = pages[2];
    await page.waitForSelector('#myDiv');
    await page.waitFor(1000);
    await page.evaluate(()=>{
        document.querySelectorAll('li')[46].setAttribute('id','xiongxin');
    });
    await page.click('#xiongxin');
    await page.waitFor(1500);
    pages = await browser.pages();
    page = pages[3];
    await page.waitForSelector('#searchBox');
    await page.waitFor(500);
    let cookies = await page.cookies();
    eventsEmitter.emit('getData',cookies[1].value,cookies[0].value);
    browser.close();
})()



